package com.skyline.common.mongo;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;

/**
 * BaseMongoDAOImpl是对BaseMongoDao的实现
 * 
 * @author Jairus Chan
 * 
 */
@Repository("mongoTemplate")
public class MongoTemplate {

	private Mongo mongo;

	@Value("${mongo.db.host}")
	private String mongoHost;

	@Value("${mongo.db.port}")
	private Integer mongoPort;


	@Value("${mongo.db.dbname}")
	private String dbName;

	@Value("${mongo.db.username}")
	private String username;

	@Value("${mongo.db.password}")
	private String password;

	private DB db;

	private boolean initaled = false;

	private static final Log LOGGER = LogFactory.getLog(MongoTemplate.class);

	public void inital() {
		if (initaled == false) {
			try {
				mongo = new Mongo(mongoHost, mongoPort);
				db = mongo.getDB(dbName);
				LOGGER.info("选择数据库--" + dbName + "。");
				boolean loginSuccess = db.authenticate(username, password.toCharArray());
				if (loginSuccess == false) {
					db = null;
					Exception e = new Exception("数据库--" + dbName + ",验证失败,请确认用户名和密码");
					LOGGER.error(e);
					throw e;
				}
				initaled = true;
				LOGGER.info("数据库--" + dbName + "认证成功。");
			} catch (Exception e) {
				LOGGER.error("数据库--" + dbName + "没有连接成功：可能原因有认证失败，服务未开启等。", e);
			}
		}
	}

	public DBCollection getCollection(String collectionName) {
		inital();
		return db.getCollection(collectionName);
	}

	@Override
	protected void finalize() {
		mongo.close();
	}

}
